<?php

class Application_Model_Weixin extends Application_Model_DomainObject {

    protected $_id;
    protected $_fromusername;
    protected $_uuchid;
    protected $_nickname;
    protected $_createtime;
    protected $_status;
    protected $_fakeid;
    protected $options = array(
        'account' => 'lijie@uuch.net',
        'password' => 'songjin345',
        'datapath' => '../data/cookie_',
        'debug' => true,
        'logcallback' => 'logdebug'
    );
    protected $domain = "http://test.uuch.com/";

    public function valid() {
        $echoStr = $_GET["echostr"];
        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    function getAutoMsg($fromUserName) {

        $autoMsg = "感谢您关注【悠奇中国】悠奇是国内领先的国际快递代理商，DHL、UPS、EMS、  Fedex等国际快递发全球低至3~5折。 可以提供任何国际快递业务咨询。
         <a href=\"http://test.uuch.com/weixin/login?uid=" . $fromUserName . "\">点击进行身份验证</a>";

        return $autoMsg;
    }

    //获取token（创建自定义菜单用）
    function getToken() {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbb43168dbbcda288&secret=798fe5f862082bbc66fc7a704d7a201c";
        return $this->get($url);
    }

    //创建自定义菜单
    function creatMenu($menu_ary) {
        foreach ($menu_ary['button'] as $key => $value) {
            if (count($value) == 2) {
                $menu_ary['button'][$key]['name'] = urlencode($value['name']);
                foreach ($value['sub_button'] as $key2 => $value2) {
                    $menu_ary['button'][$key]['sub_button'][$key2]['name'] = urlencode($value2['name']);
                }
            } elseif (count($value) == 3) {
                $menu_ary['button'][$key]['name'] = urlencode($value['name']);
            }
        }
        $str = urldecode(json_encode($menu_ary));
        $token_ary = $this->getToken();
        $token = $token_ary['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$token}";
        return $this->post($url, $str);
    }

    //删除自定义菜单
    function deleteMenu() {
        $token_ary = $this->getToken();
        $token = $token_ary['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={$token}";
        return $this->get($url);
    }

    // get方法，供类内部方法使用
    protected function get($url) {
        $curlObj = curl_init();    //初始化curl，
        curl_setopt($curlObj, CURLOPT_URL, $url);   //设置网址
        curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);  //将curl_exec的结果返回
        curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curlObj, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curlObj, CURLOPT_HEADER, 0);         //是否输出返回头信息
        $response = curl_exec($curlObj);   //执行
        curl_close($curlObj);          //关闭会话
        return json_decode($response, true);
    }

    //post数据
    protected function post($url, $post_data) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response = curl_exec($curl);
        $result = json_decode($response, true);
        $error = curl_error($curl);
        return $error ? $error : $result;
    }

    public function responseWeixin() {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $object = "";
        if (!empty($postStr)) {
            $object = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        }
        $msgType = trim($object->MsgType);

        if ($msgType == "event") {
            $this->handleEvent($object);
        }

        if ($msgType == "text") {
            $content = $this->getAutoMsg($object->FromUserName);
            echo $this->responseText($object, $content);
        }
    }

    private function responseStoreItemMsg($postObj, $model) {
        $result = self::getTopStoreItem($model->uuchid, 3);
        if ($result == null) {
            $content = $this->getAutoMsg($postObj->FromUserName);
            return $this->responseText($postObj, $content);
        }

        $textTpl = " <xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount><![CDATA[%d]]></ArticleCount>
                <Articles>  %s </Articles>
                <FuncFlag>1</FuncFlag>
                </xml> ";
        $itemContent = '<item>
                <Title><![CDATA[你好,最近10条仓库信息]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[http://test.uuch.com/images/share/logo.gif]]></PicUrl>
                <Url><![CDATA[http://test.uuch.com/weixin/storeitem?fromusername=' . $postObj->FromUserName . ']]></Url>
                </item>';
        foreach ($result as $item) {
            $itemContent = $itemContent . '<item>
                <Title><![CDATA[' . "编号:" . $item->id . " \n 名称:" . $item->productName . " \n 物品净重:" . $item->weight
                    . " \n 体积重量:" . $item->VolumeWeight . " \n 入库时间:" . date('Y-m-d', strtotime($item->dateInStore)) . ']]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[http://test.uuch.com/images/popularize/pic2.jpg]]></PicUrl>
                <Url><![CDATA[http://test.uuch.com/weixin/storeitemdetail?id=' . $item->id . '&fromusername=' . $model->nickname . ']]></Url>
                </item>';
        }
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "news", count($result) + 1, $itemContent);
        return $resultStr;
    }

    public static function getTopStoreItem($uuchid, $rowcount) {
        $model = new Application_Model_DbTable_Weixin();
        $result = $model->getTopStoreItem($uuchid, $rowcount);
        return $result['list'];
    }

    private function responseExpressFree($postObj) {
        $textTpl = " <xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount><![CDATA[%d]]></ArticleCount>
                <Articles>  %s </Articles>
                <FuncFlag>1</FuncFlag>
                </xml> ";

        $itemContent = '<item>
                <Title><![CDATA[查询运费]]></Title>
                <Description><![CDATA[查询运费业务描述]]></Description>
                <PicUrl><![CDATA[http://test.uuch.com/images/share/logo.gif]]></PicUrl>
                <Url><![CDATA[http://test.uuch.com/tool/express]]></Url>
                </item>';

        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "news", 1, $itemContent);
        return $resultStr;
    }

    private function responseVistoringService($postObj) {
        $textTpl = " <xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount><![CDATA[%d]]></ArticleCount>
                <Articles>  %s </Articles>
                <FuncFlag>1</FuncFlag>
                </xml> ";

        $itemContent = '<item>
                <Title><![CDATA[上门服务]]></Title>
                <Description><![CDATA[上门服务业务描述]]></Description>
                <PicUrl><![CDATA[http://test.uuch.com/images/share/logo.gif]]></PicUrl>
                <Url><![CDATA[http://test.uuch.com/store/up]]></Url>
                </item>';

        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "news", 1, $itemContent);
        return $resultStr;
    }

    private function responseWaybillMsg($postObj, $model) {
        $result = self::getTopWayBill($model->uuchid, 3);
        if ($result == null) {
            $content = $this->getAutoMsg($postObj->FromUserName);
            return $this->responseText($postObj, $content);
        }

        $textTpl = " <xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <ArticleCount><![CDATA[%d]]></ArticleCount>
                <Articles>  %s </Articles>
                <FuncFlag>1</FuncFlag>
                </xml> ";

        $itemContent = '<item>
                <Title><![CDATA[你好,最近10条运单信息]]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[http://test.uuch.com/images/share/logo.gif]]></PicUrl>
                <Url><![CDATA[http://test.uuch.com/weixin/waybill?fromusername=' . $postObj->FromUserName . ']]></Url>
                </item>';

        foreach ($result as $item) {
            $itemContent = $itemContent . '<item>
                <Title><![CDATA[' . "运单:" . $item->billNo . " \n " . "时间:" . date('Y-m-d', strtotime($item->dateCreated)) .
                    " \n " . "方式:" . $item->getShipName() . " \n " . "状态:" . $item->getStatusName() . " \n "
                    . "金额:" . $item->shipMoney . ']]></Title>
                <Description><![CDATA[]]></Description>
                <PicUrl><![CDATA[http://test.uuch.com/images/popularize/pic2.jpg]]></PicUrl>
                <Url><![CDATA[http://test.uuch.com/weixin/waybilldetail?billNo=' . $item->billNo . '&fromusername=' . $postObj->FromUserName . ']]></Url>
                </item>';
        }
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), "news", count($result) + 1, $itemContent);
        return $resultStr;
    }

    function responseText($postObj, $content) {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";
        $msgType = "text";
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $content);
        return $resultStr;
    }

    private function handleEvent($object) {
        if ($object->Event == "subscribe") {
            $contentStr = $this->getAutoMsg($object->FromUserName);
            echo $this->responseText($object, $contentStr);
        }

        if ($object->Event == "CLICK" && $object->EventKey == "expressFree") {
            echo $this->responseExpressFree($object);
        }
        if ($object->Event == "CLICK" && $object->EventKey == "vistoringService") {
            echo $this->responseVistoringService($object);
        }

        $user = $this->getWeixin($object->FromUserName);
        if ($user == null || $user->uuchid == 0) {
            $contentStr = $this->getAutoMsg($object->FromUserName);
            echo $this->responseText($object, $contentStr);
        }
        if ($object->Event == "CLICK" && $object->EventKey == "wayBill") {
            echo $this->responseWaybillMsg($object, $user);
        }
        if ($object->Event == "CLICK" && $object->EventKey == "storeItem") {
            echo $this->responseStoreItemMsg($object, $user);
        }
        
        $contentStr = $this->getAutoMsg($object->FromUserName);
        echo $this->responseText($object, $contentStr);
    }

    public static function getTopWayBill($userId, $rowCount) {
        $model = new Application_Model_DbTable_Weixin();
        $result = $model->getTopWaybill($userId, $rowCount);
        return $result['list'];
    }

    public static function getWeixin($fromusername) {
        $model = new Application_Model_DbTable_Weixin();
        return $model->getByUid($fromusername);
    }

    public static function getStoreitemDetail($id) {
        $where[" id = "] = $id;
        return Application_Model_StoreItem::getDao()->queryOne($where);
    }

    private function checkSignature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

}

?>